import dayjs from "dayjs"
import { md5 } from "./md5"
import XEUtils from "xe-utils"
const LV_USER_SIGN_KEY: string = "69OkMSq6f7"

interface GetParamType {
	[key: string]: any
}

interface PostParamType {
	[key: string]: any
}
// 在 setup 函数中定义一个方法来格式化日期
export const formatTimeWithoutSeconds = (dateString: string): string => {
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = addZero(date.getMonth() + 1) // 月份从0开始，需要加1
	const day = addZero(date.getDate())
	const hours = addZero(date.getHours())
	const minutes = addZero(date.getMinutes())

	return `${year}-${month}-${day} ${hours}:${minutes}`
}

export function processQuery(getParam: GetParamType): GetParamType {
	if (typeof getParam["sign"] !== "undefined") {
		delete getParam["sign"]
	}
	return getParam
}

export function extend(data: any, dataExtend: any): any {
	let res: any = {}
	for (let key in data) {
		res[key] = data[key]
	}
	for (let key in dataExtend) {
		res[key] = dataExtend[key]
	}
	return res
}

function generateApiSign(getParam: GetParamType, postParam: PostParamType, secretKey: string): string {
	let data = extend(getParam, postParam)
	let orderedData: any = {}
	let values: string[] = []

	Object.keys(data)
		.sort()
		.forEach((key) => {
			orderedData[key] = data[key]
			values.push(key + "=" + data[key])
		})

	let params_string: string = values.join("&")
	return md5(params_string + "&key=" + secretKey)
}

export function addSignForLvUser(
	getParam: GetParamType = {},
	postParam: PostParamType = {},
	callbackFunc?: (signData: string) => void
): string {
	getParam = processQuery(getParam)
	let signData: string = generateApiSign(getParam, postParam, LV_USER_SIGN_KEY)
	callbackFunc && callbackFunc(signData)
	return signData
}

export function uploadCdnParams(
	imgBase64: string,
	fileName: string,
	timestamp: number
): { query: GetParamType; post: PostParamType } {
	imgBase64 = encodeURIComponent(imgBase64)
	const dataStr: string = `image_base64=${imgBase64}&image_file_name=${fileName}&timestamp=${timestamp}&key=${LV_USER_SIGN_KEY}`
	const sign: string = md5(dataStr)
	let query: GetParamType = {
		sign,
		timestamp,
	}
	let post: PostParamType = {
		image_base64: imgBase64,
		image_file_name: fileName,
	}

	return { query, post }
}

export function getCurrentPageUrl(): string {
	let pages: any[] = getCurrentPages()
	let values: string[] = []
	let params_string: string = ""

	let currentPage = pages[pages.length - 1]
	if (currentPage.options) {
		Object.keys(currentPage.options).forEach((key) => {
			values.push(key + "=" + currentPage.options[key])
		})
		params_string = values.join("&")
	}

	return currentPage.route + "?" + params_string
}

export function setStorageSync(key: string, value: any): void {
	uni.setStorageSync(key, value)
}

export function getStorageSync(key: string): any {
	return uni.getStorageSync(key)
}

export function addZero(num: number): string {
	if (num < 10) {
		return "0" + num
	}
	return num.toString()
}

// 四舍五入金额，每隔三位逗号分隔，默认两位小数
export const formatAmount = (num: number) => {
	num = Number(num)
	if (isNaN(num)) {
		return "-"
	}
	const result = num / 100
	// 检查是否有小数部分
	const hasDecimal = result % 1 !== 0
	let digits = 0
	if (hasDecimal) {
		digits = String(Number(result)).split(".")[1].length
	}
	if (result) {
		return XEUtils.commafy(XEUtils.toNumber(result), { digits })
	} else {
		return result
	}
}

/**
 * 验证手机格式
 */
export function mobile(value: string) {
	return /^1[23456789]\d{9}$/.test(value)
}

/**
 * 验证十进制数字
 */
export function isNumber(value: string): boolean {
	// eslint-disable-next-line no-useless-escape
	return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
}

/**
 * 是否数组
 */
export function isArray(value: any) {
	if (typeof Array.isArray === "function") {
		return Array.isArray(value)
	}
	return Object.prototype.toString.call(value) === "[object Array]"
}

/**
 * 是否对象
 */
export function isObject(value: any): value is Record<any, any> {
	return typeof value === "object" && value !== null
}

/**
 * 是否定义
 * @param {any} value
 */
export function isDef(value: any): boolean {
	return value !== undefined && value !== null
}
// 排序
export function arrSortByKey(array: any[], property: string | number, desc = false) {
	return array.sort(function (a: { [x: string]: any }, b: { [x: string]: any }) {
		let value1 = a[property],
			value2 = b[property]
		if (desc) {
			//升序
			return value1 - value2
		} else {
			//降序
			return value2 - value1
		}
	})
}

export function today() {
	let today = new Date(),
		month = today.getMonth() + 1,
		date = today.getDate()
	return `${today.getFullYear()}-${month < 10 ? "0" + month : month}-${date < 10 ? "0" + date : date}`
}

export function getShortDate(date: string) {
	return dayjs(date).format("M-D")
}

export function getShortTime(date: string) {
	return dayjs(date).format("HH:mm")
}

//处理起始时间
export function getRangeDate(startDate: string, endDate: string) {
	return startDate == endDate ? startDate : `${startDate} 至 ${endDate}`
}
//复制
export function copyData(data: string) {
	uni.setClipboardData({
		data,
	})
}

//划线价大于实际价才展示
export function showListPrice(listPrice: number, realPrice: number) {
	return +listPrice > +realPrice
}

// 本地缓存处理
export function getLocalStorage(key: string) {
	return uni.getStorageSync(key)
}
export function setLocalStorage(key: string, value: any) {
	return uni.setStorageSync(key, value)
}
export function removeLocalStorage(key: string) {
	return uni.removeStorageSync(key)
}

//日期特殊化处理
export const formatDateToWeek = (date: string) => {
	if (!date) return "-"
	if (date === "1970-01-01 00:00:00" || date === "1970-01-01") return "-"
	const today = dayjs().startOf("day")
	const tomorrow = today.add(1, "day").startOf("day")
	const givenTime = dayjs(date)
	if (givenTime.isSame(today, "day")) {
		return "今天 "
	} else if (givenTime.isSame(tomorrow, "day")) {
		return "明天"
	} else {
		const num = dayjs(date).day()
		return {
			0: "周日",
			1: "周一",
			2: "周二",
			3: "周三",
			4: "周四",
			5: "周五",
			6: "周六",
		}[num]
	}
}
// end

// 处理html内容
export function processHtmlContent(htmlContent: string) {
	// 使用正则表达式处理图片标签，限制其大小
	const imgRegex = /<img[^>]*>/g
	return htmlContent.replace(imgRegex, (match) => {
		return match.replace(/(<img.*?)(>)/i, `$1 style="max-width: 100%; height: auto; display: block;"$2`)
	})
}

/**
 * 通过服务端生成的小程序码
 */
export const getIdBYScene = (scene: any, key = "id") => {
	let id = ""
	if (scene) {
		let sceneArr = scene.split("&")
		sceneArr.map((val: any) => {
			let itemArr = val.split("=")
			if (itemArr[0] == key) {
				id = itemArr[1]
			}
		})
	}
	return id
}
